﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using AjaxControlToolkit.Design;

public partial class UserControl_ControlNhapHangTuNCC : System.Web.UI.UserControl
{
    ClassExecute.ClassExecute dt;
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
    double priceTotal = 0;
    double distAmt = 0;
    protected void Page_Load(object sender, EventArgs e)    
   {
        if (!IsPostBack)
        {
           // NhaCungCap(Session["sitecode"].ToString());
            ClearAdd(); 
            
        }
        gridProductEmpty();

        CallAutoComplate();
        
    }

    void CallAutoComplate()
    {
        try
        {
            AutoCompleteExtender AutoComMaHangInput = grvProduct.FooterRow.FindControl("txtMaHangInput_AutoCompleteExtender") as AutoCompleteExtender;
            AutoComMaHangInput.ContextKey = ddlNCC.SelectedValue.ToString();
        }
        catch {
            return;
        }
    }
    void ClearAdd()
    {
        TabContainer1.ActiveTabIndex = 0;
        txtSoNV.Text = "New";
        txtDiscAmt.Text = "0";
        txtDocTot.Text = "0";
        txtDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
        ViewState["flag"] = true;
        BindKhoiTao();

        lblMsg.Text = "";
        lblMsg.Visible = true;
        btnSave.Text = "Lưu";
        btnDelete.Visible = false;
    }

    protected void imgBtnAdd_Click(object sender, ImageClickEventArgs e)
    {
        ClearAdd();
        CallAutoComplate();
    }
    void ShowMessageBox(string text)
    {
        MessageBox.Text = text;
        MessageBox.ShowOnPageLoad = true;
    }
    public int CompareDate(string sdate1, string sdate2)
    {
        DateTime date1 = new DateTime(int.Parse(sdate1.Substring(6, 4)), int.Parse(sdate1.Substring(3, 2)), int.Parse(sdate1.Substring(0, 2)));
        DateTime date2 = new DateTime(int.Parse(sdate2.Substring(6, 4)), int.Parse(sdate2.Substring(3, 2)), int.Parse(sdate2.Substring(0, 2)));
        int result = DateTime.Compare(date1, date2);
        return result;

        //if (result < 0)
        //    relationship = "sdate1 is earlier than";
        //else if (result == 0)
        //    relationship = "is the same time as";
        //else
        //    relationship = "sdate 1 is later than";

    }
    
    protected void ImgBtnRequest_Click(object sender, ImageClickEventArgs e)
    {

        BindGridSearch(Session["sitecode"].ToString());
        CallAutoComplate();
    }
    void NhaCungCap(string sitecode)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getVendor", CommandType.StoredProcedure,
                new SqlParameter("@sitecode", sitecode));
            dt.BindDropDownList(db, ddlNCC, "vendorkey", "vendorname");
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }

    }
    //protected void txtMaHang_TextChanged(object sender, EventArgs e)
    //{
    //    try
    //    {
    //        string Chuoi = txtMaHang.Text;
    //        int index = Chuoi.IndexOf("|");
    //        txtMaHang.Text = Chuoi.Substring(0, index - 1);
    //        txtTenHang.Text = Chuoi.Substring(index + 2, Chuoi.Length - index - 2);
    //        txtCost.Focus();
            

    //    }
    //    catch
    //    {
    //        return;
    //    }
    //}
    
    //void UpdateGridProduct()
    //{
    //    DataTable table = new DataTable();
    //    if (ViewState["KhoHangTemp"] != null)
    //    {
    //        table = (DataTable)ViewState["KhoHangTemp"];
    //        foreach (DataRow dr in table.Rows)
    //        {
    //            if (dr[0].ToString() == txtMaHang.Text)
    //            {
    //                dr[2] = Double.Parse(dr[2].ToString()) + Double.Parse(txtSoLuong.Text);
    //                dr[3] = Double.Parse(txtCost.Text);
    //                //thành tiền trên dòng = giá*số lượng(100-%CK)/100
    //                dr[5] = Double.Parse(dr[2].ToString()) * Double.Parse(txtCost.Text) * (100 -float.Parse(dr[4].ToString()))/ 100;
    //                //tiền CK=số lượng*giá*%CK/100
    //                dr[6] = Double.Parse(dr[2].ToString()) * Double.Parse(txtCost.Text) * float.Parse(dr[4].ToString())/ 100 ;
    //                ViewState["KhoHangTemp"] = table;
    //                grvProduct.DataSource = ViewState["KhoHangTemp"];
    //                grvProduct.DataBind();
    //                return;
    //            }
    //        }

    //        DataRow row = table.NewRow();
    //        //Fill All Columns with Data
           
    //        row[0] = txtMaHang.Text;
    //        row[1] = txtTenHang.Text;
    //        row[2] = Double.Parse(txtSoLuong.Text);
    //        row[3] = Double.Parse(txtCost.Text);
    //        row[4] = 0;
    //        row[5] = Double.Parse(txtSoLuong.Text) * Double.Parse(txtCost.Text) * 100 / 100;
    //        row[6] = 0;
    //        table.Rows.Add(row);
    //    }
    //    else
    //    {


    //        DataColumn col1 = new DataColumn("Mã hàng");
    //        DataColumn col2 = new DataColumn("Tên hàng");
    //        DataColumn col3 = new DataColumn("Số lượng");
    //        DataColumn col4 = new DataColumn("Đơn giá");
    //        DataColumn col5 = new DataColumn("Chiết khấu");
    //        DataColumn col6 = new DataColumn("Thành tiền");
    //        DataColumn col7 = new DataColumn("Tiền chiết khấu");

    //        col1.DataType = System.Type.GetType("System.String");
    //        col2.DataType = System.Type.GetType("System.String");
    //        col3.DataType = System.Type.GetType("System.Double");
    //        col4.DataType = System.Type.GetType("System.Double");
    //        col5.DataType = System.Type.GetType("System.Double");
    //        col6.DataType = System.Type.GetType("System.Double");
    //        col7.DataType = System.Type.GetType("System.Double");

    //        table.Columns.Add(col1);
    //        table.Columns.Add(col2);
    //        table.Columns.Add(col3);
    //        table.Columns.Add(col4);
    //        table.Columns.Add(col5);
    //        table.Columns.Add(col6);
    //        table.Columns.Add(col7);

    //        //Create a Row in the DataTable table
    //        DataRow row = table.NewRow();
    //        //Fill All Columns with Data
    //        row[col1] = txtMaHang.Text;
    //        row[col2] = txtTenHang.Text;
    //        row[col3] = Double.Parse(txtSoLuong.Text);
    //        row[col4] = Double.Parse(txtCost.Text);
    //        row[col5] = 0;
    //        row[col6] = Double.Parse(txtSoLuong.Text) * Double.Parse(txtCost.Text) ;
    //        row[col7] = 0;
    //        table.Rows.Add(row);

    //        ViewState["KhoHangTemp"] = table;
    //    }
    //    grvProduct.DataSource = ViewState["KhoHangTemp"];
    //    grvProduct.DataBind();

    //    txtMaHang.Text = "";
    //    txtTenHang.Text = "";
    //    txtCost.Text = "0";
    //    txtSoLuong.Text = "";
    //    txtMaHang.Focus();
    //}
    protected void grvProduct_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            string keys = grvProduct.DataKeys[e.RowIndex].Value.ToString();
            TextBox txtSL = (TextBox)grvProduct.Rows[e.RowIndex].FindControl("txtSL");
            TextBox txtDG = (TextBox)grvProduct.Rows[e.RowIndex].FindControl("txtDG");
            TextBox txtCK = (TextBox)grvProduct.Rows[e.RowIndex].FindControl("txtCK");

            
            if ((txtSL.Text == "") || (txtSL.Text == "0"))
            {
                txtSL.Text = "1";
            }
            if (txtDG.Text == "" )
            {
                txtDG.Text = "0";
            }
            if ((txtCK.Text == "") || (txtCK.Text == "0"))
            {
                txtCK.Text = "0";
            }

            Double soluong = Double.Parse(txtSL.Text);
            Double dongia = Double.Parse(txtDG.Text);
            Double chietkhau = Double.Parse(txtCK.Text);

            DataTable table = new DataTable();
            table = (DataTable)ViewState["KhoHangTemp"];

            foreach (DataRow dr in table.Rows)
            {
                if (dr[0].ToString() == keys)
                {
                    dr[2] = soluong;
                    dr[3] = dongia;
                    dr[4] = chietkhau;
                    dr[5] = soluong * dongia * (100 - chietkhau) / 100;
                    dr[6] = soluong * dongia * chietkhau / 100;
                    table.AcceptChanges();
                    ViewState["KhoHangTemp"] = table;

                    grvProduct.EditIndex = -1;
                    grvProduct.DataSource = ViewState["KhoHangTemp"];
                    grvProduct.DataBind();
                }
            }
            CallAutoComplate();

        }
        catch (Exception ex)
        {
            CallAutoComplate();

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }   
    }
    protected void grvProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string keys = grvProduct.DataKeys[e.RowIndex].Value.ToString();

        DataTable table = new DataTable();
        table = (DataTable)ViewState["KhoHangTemp"];

        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            if (dr[0].ToString() == keys)
            {
                table.Rows[i].Delete();
                table.AcceptChanges();
                ViewState["KhoHangTemp"] = table;
                grvProduct.EditIndex = -1;
                //Kiểm tra xem nếu đã xóa hết
                if (table.Rows.Count > 0)
                {
                    grvProduct.DataSource = ViewState["KhoHangTemp"];
                    grvProduct.DataBind();
                }
                else
                {
                    BindKhoiTao();    
                }
                CallAutoComplate();
                return;
            }
            i++;
        }        
    }
    protected void grvProduct_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grvProduct.EditIndex = -1;
        grvProduct.DataSource = ViewState["KhoHangTemp"];
        grvProduct.DataBind();
       
        CallAutoComplate();
    }
    protected void grvProduct_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grvProduct.EditIndex = e.NewEditIndex;
        grvProduct.DataSource = ViewState["KhoHangTemp"];
        grvProduct.DataBind();

        CallAutoComplate();
    }
    protected void grvSearch_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {
                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                Label lblSoNV = (Label)grv.FindControl("lblSoNV");

                DataTable dbMaster = dt.Get_Data_DataTable(str, ref error, "k_getMasterReceiveProduct", CommandType.StoredProcedure,
                   new SqlParameter("@tranno", lblSoNV.Text));

                txtSoNV.Text = dbMaster.Rows[0]["vouchno"].ToString();
                txtDate.Text = dbMaster.Rows[0]["invdate"].ToString();
                txtDocTot.Text = dbMaster.Rows[0]["vouchtotal"].ToString();
                txtDiscAmt.Text = dbMaster.Rows[0]["discamt"].ToString();

                DataTable dbDetail = dt.Get_Data_DataTable(str, ref error, "k_getDetailMasterReceiveProduct", CommandType.StoredProcedure,
                  new SqlParameter("@tranno", lblSoNV.Text),
                  new SqlParameter("@siteCode", Session["sitecode"].ToString()));

                if (dbDetail.Rows.Count > 0)
                {
                    ViewState["KhoHangTemp"] = dbDetail;
                    grvProduct.DataSource = ViewState["KhoHangTemp"];
                    grvProduct.DataBind();
                }

                grvSearch.DataSource = null; 
                grvSearch.DataBind();

                ViewState["flag"] = false;

                //Edit
                lblMsg.Text = "";
                lblMsg.Visible = false;
                btnSave.Text = "Cập nhật";
                btnDelete.Visible = true;
                //End Edit

                TabContainer1.ActiveTabIndex = 0;

            }
            
            CallAutoComplate();
        }
        catch (Exception ex)
        {
            CallAutoComplate();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
   
    protected void grvSearch_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvSearch.PageIndex = e.NewPageIndex;
        BindGridSearch(Session["sitecode"].ToString());
        CallAutoComplate();
    }
    void BindGridSearch(string sitecode)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "k_searchNVNhanHangTuNCC", CommandType.StoredProcedure,
                new SqlParameter("@siteCode", sitecode));
            grvSearch.DataSource = db;
            grvSearch.DataBind();
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvProduct_RowDataBound1(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            priceTotal += double.Parse(DataBinder.Eval(e.Row.DataItem, "Thành tiền").ToString());
           
            if (priceTotal > 0)
            {
                txtDocTot.Text = string.Format("{0:#,#}", priceTotal);
            }
            else
            {
                txtDocTot.Text = priceTotal.ToString();
            }

            distAmt += double.Parse(DataBinder.Eval(e.Row.DataItem, "Tiền chiết khấu").ToString());
            if (distAmt > 0)
            {
                txtDiscAmt.Text = string.Format("{0:#,#}", distAmt);
            }
            else
            {
                txtDiscAmt.Text = distAmt.ToString();
            }
        }
    }
    void gridProductEmpty()
    {
        if (grvProduct.Rows[0].Cells[0].Text == "Thêm mặt hàng")
        {
            int TotalColumns = grvProduct.Rows[0].Cells.Count;
            grvProduct.Rows[0].Cells.Clear();
            grvProduct.Rows[0].Cells.Add(new TableCell());
            grvProduct.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            grvProduct.Rows[0].Cells[0].Text = "Thêm mặt hàng";
        }
    }

    void BindKhoiTao()
    {
        //dt = new ClassExecute.ClassExecute();
        try
        {
            //DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_getProductToGetFromNCC]", CommandType.StoredProcedure,
            //    new SqlParameter("@Sitecode", Session["sitecode"].ToString()),
            //    new SqlParameter("@vendorkey", ddlNCC.SelectedValue.ToString()));
            
            //if(db.Rows.Count>0)
            //{
                
                //if (ViewState["KhoHangTemp"] != null)
                //{
                //    ViewState["KhoHangTemp"] = null;
                //}
                //ViewState["KhoHangTemp"] = db;
                //grvProduct.DataSource = ViewState["KhoHangTemp"];
            //}
            //else
            //{
            //    
            //    grvProduct.DataSource = null;
            //    ShowMessageBox("Bạn chưa khai báo mặt hàng thuộc hàng cung cấp này");
            //}
            //grvProduct.DataBind();
            
            DataTable dtChiTietDH = new DataTable();
            dtChiTietDH = dtChiTietDonHang();
                          
            ViewState["KhoHangTemp"] = dtChiTietDonHang();            

            dtChiTietDH.Rows.Add(dtChiTietDH.NewRow());
            dtChiTietDH.Rows[0][0] = "";
            dtChiTietDH.Rows[0][1] = "";
            dtChiTietDH.Rows[0][2] = "0";
            dtChiTietDH.Rows[0][3] = "0"; 
            dtChiTietDH.Rows[0][4] = "0";
            dtChiTietDH.Rows[0][5] = "0";
            dtChiTietDH.Rows[0][6] = "0";
            grvProduct.DataSource = dtChiTietDH;
            grvProduct.DataBind();

            int TotalColumns = grvProduct.Rows[0].Cells.Count;
            grvProduct.Rows[0].Cells.Clear();
            grvProduct.Rows[0].Cells.Add(new TableCell());
            grvProduct.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            grvProduct.Rows[0].Cells[0].Text = "Thêm mặt hàng";
        }
        catch
        {
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (grvProduct.Rows.Count > 0)
        {
            int checkkhoaso = CompareDate(txtDate.Text, Session["workingday"].ToString());
            if (checkkhoaso < 0)
            {
                //ShowMessageBox("Ngày bạn chọn nhỏ hơn ngày đã khóa sổ trong hệ thống,ngày khóa sổ của bạn là " + Session["workingday"].ToString());
                lblMsg.Text = "Ngày bạn chọn nhỏ hơn ngày đã khóa sổ trong hệ thống,ngày khóa sổ của bạn là " + Session["workingday"].ToString();
                lblMsg.Visible = true;
                txtDate.Focus();
            }
            else
            {
                dt = new ClassExecute.ClassExecute();
                string DocNo = "";
                try
                {


                    if ((bool)ViewState["flag"])
                    {
                        DocNo = dt.GetDataDepend(str, "[k_getDocNoGetFromBranch]", CommandType.StoredProcedure, ref error,
                            new SqlParameter("@sitecode", Session["sitecode"].ToString()));
                        ViewState["flag"] = true;
                    }
                    else
                    {
                        DocNo = txtSoNV.Text;
                    }

                    //lưu vào table ReceiveProduct(arhdr)
                    int j = 1;
                    bool kqReceiveProduct = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_insertReceiveProduct", ref error,
                        new SqlParameter("@Vendorkey", ddlNCC.SelectedValue.ToString()),
                        new SqlParameter("@tranno", DocNo),
                        new SqlParameter("@invdate", txtDate.Text),
                        new SqlParameter("@doctot", double.Parse(txtDocTot.Text)),
                        new SqlParameter("@discamt", double.Parse(txtDiscAmt.Text)),
                        new SqlParameter("@Recuser", Session["user"].ToString()),
                        new SqlParameter("@i", j),
                        new SqlParameter("@sitecode", Session["sitecode"].ToString()));

                    //lưu vào table ReceiveProductDetail(arlin)
                    int i = 1;

                    foreach (GridViewRow grv in grvProduct.Rows)
                    {
                        Label lblMaHang = (Label)grv.FindControl("lblMaHang");
                        Label lblSL = (Label)grv.FindControl("lblSL");
                        Label lblDG = (Label)grv.FindControl("lblDG");
                        Label lblCK = (Label)grv.FindControl("lblCK");
                        Label lblTenHang = (Label)grv.FindControl("lblTenHang");
                        Label lblThanhTien = (Label)grv.FindControl("lblThanhTien");
                        Label lblTienDuocChietKhau = (Label)grv.FindControl("lblTienCK");
                        Label lblLastCost = (Label)grv.FindControl("lblLastCost");
                        if ((lblThanhTien.Text == "") || (lblThanhTien.Text == null))
                        {
                            lblThanhTien.Text = "0";
                        }
                        if ((lblLastCost.Text == "") || (lblLastCost.Text == null))
                        {
                            lblLastCost.Text = "0";
                        }
                        bool kqReceiveProductDetail = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_insertReceiveProductDetail", ref error,
                            new SqlParameter("@ItemKey", lblMaHang.Text),
                            new SqlParameter("@tranno", DocNo),
                            new SqlParameter("@description", lblTenHang.Text),
                            new SqlParameter("@costamt", float.Parse(lblDG.Text)),
                            new SqlParameter("@lastcost", float.Parse(lblLastCost.Text)),
                            new SqlParameter("@shipqty", float.Parse(lblSL.Text)),
                            new SqlParameter("@disc", float.Parse(lblCK.Text)),
                            new SqlParameter("@docdate", txtDate.Text),
                            new SqlParameter("@i", i),
                            new SqlParameter("@PrDisc", float.Parse(lblTienDuocChietKhau.Text)),
                            new SqlParameter("@sitecode", Session["sitecode"].ToString()),
                            new SqlParameter("@doctot", float.Parse(lblThanhTien.Text)));
                        i++;
                    }


                    //grvProduct.DataSource = null;
                    //grvProduct.DataBind();

                    //txtSoNV.Text = "";

                    //txtDate.Text = Session["workingday"].ToString();

                    //txtDiscAmt.Text = "0";
                    //txtDocTot.Text = "0";

                    if (ViewState["KhoHangTemp"] != null)
                    {
                        ViewState["KhoHangTemp"] = null;

                    }
                    
                    //ShowMessageBox("Lưu thông tin thành công");

                    txtSoNV.Text = "New";
                    ViewState["flag"] = true;
                   
                    //ClearAdd();
                    lblMsg.Text = "Hoàn thành lưu hóa đơn";
                    lblMsg.Visible = true;

                    CallAutoComplate();
                }
                catch (Exception ex)
                {
                    CallAutoComplate();
                    //ShowMessageBox("Hệ thống đang bảo trì");
                    lblMsg.Text = "Hệ thống đang bảo trì";
                    lblMsg.Visible = true;

                    string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
                }
            }
        }
        else
        {
            CallAutoComplate();
            //ShowMessageBox("Nghiệp vụ chưa được khởi tạo");
            lblMsg.Text = "Nghiệp vụ chưa được khởi tạo";
            lblMsg.Visible = true;

        }
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_deteleNVReceiveProduct", ref error,
                 new SqlParameter("@vouchno", txtSoNV.Text));
            if (kq)
            {
                //ShowMessageBox("Xóa nghiệp vụ nhận hàng từ nhà cung cấp thành công");
                ClearAdd();
                lblMsg.Text = "Xóa nghiệp vụ nhận hàng từ nhà cung cấp thành công";
                lblMsg.Visible = true;
            }
            CallAutoComplate();
        }
        catch (Exception ex)
        {
            CallAutoComplate();
            //ShowMessageBox("Hệ thống đang bảo trì");
            lblMsg.Text = "Hệ thống đang bảo trì";
            lblMsg.Visible = true;

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }

    protected void txtMaHangInput_TextChanged(object sender, EventArgs e)
    {

        try
        {
            gridProductEmpty();            

            TextBox txtMaMHInput = grvProduct.FooterRow.FindControl("txtMaHangInput") as TextBox;
            TextBox txtTenHangInput = grvProduct.FooterRow.FindControl("txtTenHangInput") as TextBox;
            TextBox txtSoLuongInput = grvProduct.FooterRow.FindControl("txtSoLuongInput") as TextBox;
            TextBox txtDonGiaInput = grvProduct.FooterRow.FindControl("txtDonGiaInput") as TextBox;
            TextBox txtChietKhauInput = grvProduct.FooterRow.FindControl("txtChietKhauInput") as TextBox;

            //TextBox txtSTChietKhauInput = grvProduct.FooterRow.FindControl("txtSTChietKhauInput") as TextBox;
            //TextBox txtThanhTienInput = grvProduct.FooterRow.FindControl("txtThanhTienInput") as TextBox;
            //TextBox txtGiaMuaLanCuoiInput = grvProduct.FooterRow.FindControl("txtGiaMuaLanCuoiInput") as TextBox;

            Label txtSTChietKhauInput = grvProduct.FooterRow.FindControl("lblSTChietKhauInput") as Label;
            Label txtThanhTienInput = grvProduct.FooterRow.FindControl("lblThanhTienInput") as Label;
            Label txtGiaMuaLanCuoiInput = grvProduct.FooterRow.FindControl("lblGiaMuaLanCuoiInput") as Label;

            //FillGrid();
            if (!txtMaMHInput.Text.Equals(String.Empty))
            {
                string str1 = txtMaMHInput.Text;
                int index = str1.IndexOf("|");
                //if (index == -1)
                {
                    dt = new ClassExecute.ClassExecute();

                    DataTable dtMH = dt.Get_Data_DataTable(str, ref error,"TTrung_getProductInforToGetFromNCC", CommandType.StoredProcedure,
                        new SqlParameter("@itemkey", str1.Substring(0, index - 1)));
                    if (dtMH.Rows.Count > 0)
                    {
                        txtMaMHInput.Text = dtMH.Rows[0]["Mã hàng"].ToString();
                        txtTenHangInput.Text = dtMH.Rows[0]["Tên hàng"].ToString();
                        txtSoLuongInput.Text = dtMH.Rows[0]["Số lượng"].ToString();
                        txtDonGiaInput.Text = dtMH.Rows[0]["Đơn giá"].ToString();
                        txtChietKhauInput.Text = dtMH.Rows[0]["Chiết khấu"].ToString();
                        txtSTChietKhauInput.Text = dtMH.Rows[0]["Tiền chiết khấu"].ToString();
                        txtThanhTienInput.Text = (Double.Parse(txtSoLuongInput.Text) * double.Parse(txtDonGiaInput.Text)).ToString(); 
                        txtGiaMuaLanCuoiInput.Text = dtMH.Rows[0]["Giá mua lần cuối"].ToString(); ;
                    }
                    else
                    {
                        //uscMsgBox1.AddMessage("Không có mặt hàng này.", uscMsgBox.enmMessageType.Error);
                        txtMaMHInput.Focus();
                        return;
                    }
                }
                //else
                //{
                //    txtMaMHInput.Text = str1.Substring(0, index - 1);
                //    txtTenHangInput.Text = str1.Substring(index + 2, str1.Length - index - 2);
                //}

                txtSoLuongInput.Focus();

                CallAutoComplate();

            }
            
        }
        catch (Exception ex)
        {
            CallAutoComplate();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);

        }
    }

    protected void txtSoLuongInput_TextChanged(object sender, EventArgs e)
    {
        gridProductEmpty();
        ChangValue();

        TextBox txtDonGiaInput = grvProduct.FooterRow.FindControl("txtDonGiaInput") as TextBox;
        txtDonGiaInput.Focus();

        CallAutoComplate();
    }

    protected void txtDonGiaInput_TextChanged(object sender, EventArgs e)
    {
        gridProductEmpty();
        ChangValue();

        TextBox txtChietKhauInput = grvProduct.FooterRow.FindControl("txtChietKhauInput") as TextBox;
        txtChietKhauInput.Focus();

        CallAutoComplate();
    }

    private void AddRowToGridProduct()
    {
        gridProductEmpty();
        //Add rowd
        TextBox txtMaMHInput = grvProduct.FooterRow.FindControl("txtMaHangInput") as TextBox;
        TextBox txtTenHangInput = grvProduct.FooterRow.FindControl("txtTenHangInput") as TextBox;
        TextBox txtSoLuongInput = grvProduct.FooterRow.FindControl("txtSoLuongInput") as TextBox;
        TextBox txtDonGiaInput = grvProduct.FooterRow.FindControl("txtDonGiaInput") as TextBox;
        TextBox txtChietKhauInput = grvProduct.FooterRow.FindControl("txtChietKhauInput") as TextBox;
        if (txtMaMHInput.Text != "" && txtTenHangInput.Text != "")
        {
            dt = new ClassExecute.ClassExecute();
            DataTable dtMH = dt.Get_Data_DataTable(str, ref error, "TTrung_getProductInforToGetFromNCC", CommandType.StoredProcedure,
                new SqlParameter("@itemkey", txtMaMHInput.Text));
            if (dtMH.Rows.Count > 0)
            {
                txtTenHangInput.Text = dtMH.Rows[0]["Tên hàng"].ToString();

                ChangValue();

                //TextBox txtSTChietKhauInput = grvProduct.FooterRow.FindControl("txtSTChietKhauInput") as TextBox;
                //TextBox txtThanhTienInput = grvProduct.FooterRow.FindControl("txtThanhTienInput") as TextBox;
                //TextBox txtGiaMuaLanCuoiInput = grvProduct.FooterRow.FindControl("txtGiaMuaLanCuoiInput") as TextBox;

                Label txtSTChietKhauInput = grvProduct.FooterRow.FindControl("lblSTChietKhauInput") as Label;
                Label txtThanhTienInput = grvProduct.FooterRow.FindControl("lblThanhTienInput") as Label;
                Label txtGiaMuaLanCuoiInput = grvProduct.FooterRow.FindControl("lblGiaMuaLanCuoiInput") as Label;


                if (ViewState["KhoHangTemp"] != null)
                {
                    DataTable dtCTDH = (DataTable)ViewState["KhoHangTemp"];
                    for (int i = 0; i < dtCTDH.Rows.Count; i++)
                    {
                        if (dtCTDH.Rows[i][0].ToString() == txtMaMHInput.Text)
                        {
                            dtCTDH.Rows.RemoveAt(i);
                            break;
                        }
                    }
                    DataRow dr = dtCTDH.NewRow();
                    dr[0] = txtMaMHInput.Text;
                    dr[1] = txtTenHangInput.Text;
                    dr[2] = txtSoLuongInput.Text;
                    dr[3] = txtDonGiaInput.Text;
                    dr[4] = txtChietKhauInput.Text;
                    dr[5] = txtThanhTienInput.Text;
                    dr[6] = txtSTChietKhauInput.Text; 
                    dr[7] = txtGiaMuaLanCuoiInput.Text;
                    dtCTDH.Rows.Add(dr);
                    ViewState["KhoHangTemp"] = dtCTDH;
                }
                else
                {
                    DataTable dtCTDH = dtChiTietDonHang();
                    DataRow dr = dtCTDH.NewRow();
                    dr[0] = txtMaMHInput.Text;
                    dr[1] = txtTenHangInput.Text;
                    dr[2] = txtSoLuongInput.Text;
                    dr[3] = txtDonGiaInput.Text;
                    dr[4] = txtChietKhauInput.Text;
                    dr[5] = txtThanhTienInput.Text;
                    dr[6] = txtSTChietKhauInput.Text;
                    dr[7] = txtGiaMuaLanCuoiInput.Text;
                    dtCTDH.Rows.Add(dr);
                    ViewState["KhoHangTemp"] = dtCTDH;
                }
                grvProduct.DataSource = ViewState["KhoHangTemp"];
                grvProduct.DataBind();

                TextBox txtMaMHInputFocus = grvProduct.FooterRow.FindControl("txtMaHangInput") as TextBox;
                txtMaMHInputFocus.Focus();
            }
        }
        CallAutoComplate();
    }
    protected void txtChietKhauInput_TextChanged(object sender, EventArgs e)
    {
        AddRowToGridProduct();
    }

    

    private DataTable dtChiTietDonHang()
    {
        DataTable dtChiTietDH = new DataTable();
        DataColumn dtc;
        
        //Tao Cot Ma Hang
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "Mã hàng";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot Ten Hang
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "Tên hàng";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot So Luong
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "Số lượng";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot Gia
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "Đơn giá";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot VAT
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "Chiết khấu";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot ThanhTien
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "Thành tiền";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot Tiền chiết khấu
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "Tiền chiết khấu";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot Giá mua lần cuối
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "Giá mua lần cuối";
        dtChiTietDH.Columns.Add(dtc);

        return dtChiTietDH;
    }

    void ChangValue()
    {
        TextBox txtSoLuongInput = grvProduct.FooterRow.FindControl("txtSoLuongInput") as TextBox;
        TextBox txtDonGiaInput = grvProduct.FooterRow.FindControl("txtDonGiaInput") as TextBox;
        TextBox txtChietKhauInput = grvProduct.FooterRow.FindControl("txtChietKhauInput") as TextBox;

        //TextBox txtSTChietKhauInput = grvProduct.FooterRow.FindControl("txtSTChietKhauInput") as TextBox;
        //TextBox txtThanhTienInput = grvProduct.FooterRow.FindControl("txtThanhTienInput") as TextBox;

        Label txtSTChietKhauInput = grvProduct.FooterRow.FindControl("lblSTChietKhauInput") as Label;
        Label txtThanhTienInput = grvProduct.FooterRow.FindControl("lblThanhTienInput") as Label;

        double soluong = 0;
        double dongia = 0;
        double chietkhau = 0;

        try
        {
            soluong = double.Parse(txtSoLuongInput.Text.Trim());
            dongia = double.Parse(txtDonGiaInput.Text.Trim());
            chietkhau = double.Parse(txtChietKhauInput.Text.Trim());
        }
        catch { }        

        txtSTChietKhauInput.Text = (soluong * dongia * chietkhau / 100).ToString();
        txtThanhTienInput.Text = (soluong * dongia * (100 - chietkhau) / 100).ToString();        
    }

    protected void btnAddItem_Click(object sender, EventArgs e)
    {
        AddRowToGridProduct();
    }
    protected void btnDefault_Click(object sender, EventArgs e)
    {
        AddRowToGridProduct();

    }
}